#include "AddCustomGlyphDialog.h"

#include <QFileDialog>
#include <QPainter>

AddCustomGlyphDialog::AddCustomGlyphDialog( QDialog * parent ) 
    : QDialog( parent )
{
    UiDialog.setupUi( this );    

    connect( UiDialog.loadBitmapButton , SIGNAL( clicked() ), this, SLOT( loadBitmap() ) );
    connect( UiDialog.startSpinBox , SIGNAL( valueChanged(int) ), this, SLOT( onDataChange() ) );
    connect( UiDialog.baselineSpinBox , SIGNAL( valueChanged(int) ), this, SLOT( onDataChange() ) );
    connect( UiDialog.advanceSpinBox , SIGNAL( valueChanged(int) ), this, SLOT( onDataChange() ) );
    connect( UiDialog.unicodeLineEdit, SIGNAL( textChanged(QString) ), this, SLOT( onUnicodeChange() ) );

    IntValidator.setRange( 0, 65536 );
    UiDialog.unicodeLineEdit->setValidator( &IntValidator );
}

void AddCustomGlyphDialog::paintEvent( QPaintEvent* event )
{
    QPainter
        painter( this );
    int
        ratio;
    QSize
        pixmap_size,
        display_size;

    pixmap_size = Pixmap.size();
    display_size = UiDialog.pixmapDisplay->size();

    if( pixmap_size.height() == 0 || pixmap_size.width() == 0 )
    {
        return;
    }

    ratio = qMin( display_size.width() / pixmap_size.width(), display_size.height() / pixmap_size.height() );

    painter.drawPixmap( QRect( UiDialog.pixmapDisplay->pos(), ratio * pixmap_size ), Pixmap, QRect( QPoint( 0, 0 ), pixmap_size ) );

    painter.setPen( Qt::blue );
    int advance = ratio * UiDialog.advanceSpinBox->value();
    int baseline = ratio * UiDialog.baselineSpinBox->value();
    int start = ratio * UiDialog.startSpinBox->value();
    painter.drawLine( UiDialog.pixmapDisplay->pos() + QPoint( start, 0 ), UiDialog.pixmapDisplay->pos() + QPoint( start, ratio * Pixmap.height() ) );
    painter.drawLine( UiDialog.pixmapDisplay->pos() + QPoint( 0, baseline ), UiDialog.pixmapDisplay->pos() + QPoint( ratio * Pixmap.width(), baseline ) );
    painter.drawLine( UiDialog.pixmapDisplay->pos() + QPoint( start + advance, 0 ), UiDialog.pixmapDisplay->pos() + QPoint( start + advance, ratio * Pixmap.height() ) );
}

void AddCustomGlyphDialog::loadBitmap()
{
    QString filename = QFileDialog::getOpenFileName( 0, tr("Load glyph"), "*.png;*.bmp" );
    
    if( !filename.isEmpty() )
    {
        Pixmap.load( filename );
    }

    repaint();
}

void AddCustomGlyphDialog::onUnicodeChange()
{
    int result = UiDialog.unicodeLineEdit->text().toInt();
        
    UiDialog.unicodeResultLabel->setText( QString( result ) );
}